/*
 * @Description: 登录相关
 * @Author: chenju
 * @Date: 2022-04-20 13:51:36
 * @LastEditors: chenju
 * @LastEditTime: 2022-05-19 14:29:50
 */
import { store } from '@/store'
import type { RouteLocationNormalized } from 'vue-router'
import { UserActionTypes } from '@/store/modules/user/action-types'
import { UserMutationTypes } from '@/store/modules/user/mutation-types'
import type { AccountLoginParams } from '@/apis/user/model/userModel'
import { LoginFactory } from './LoginFactory.class'
import type { UrlTokenParamsType, LoginType, LoginSource } from './LoginFactory.class'

export const useAboutLogin = () => {
  console.log('useAboutLogin router')
  async function handleLoginReq(
    userInfo: AccountLoginParams | UrlTokenParamsType,
    loginType: LoginType,
    loginSource: LoginSource
  ) {
    console.log('handleLoginReq', userInfo, loginType)
    return LoginFactory.handleLogin(userInfo, loginType, loginSource)
  }

  // 处理登出的跳转
  function handleLogoutJump() {
    console.log('handleLogoutJump')
    LoginFactory.GetInstanceByUserType(store.state.user.userType).handleLogout()
  }

  // 路由守卫没有url带token时的用户类型判断
  // 是否需要跳转到外部登录页
  function handleRouterGuardHasNotToken() {
    console.log('handleRouterGuardHasNotToken', store.state.user.userType)
    const loginInstance = LoginFactory.GetInstanceByUserType(store.state.user.userType)
    if (loginInstance.logoutUrl) {
      loginInstance.handleLogout()
    }
    return !!loginInstance.logoutUrl
  }

  // 处理带着token的url（即需要直接跳转到login页面并保留url信息）
  function handleJumpWithToken(to: RouteLocationNormalized) {
    console.log('handleJumpWithToken', to, to.query)
    // 处理带着token的url的规则校验、用户类型设置、清空当前登录信息（带着token的url会替代掉当前登录的用户）
    const loginInstance = LoginFactory.GetInstanceByLocationQuery(to.query)
    if (loginInstance) {
      store.dispatch(UserActionTypes.ACTION_CLEAR_LOGIN_INFO)
      store.commit(UserMutationTypes.SET_USER_TYPE, loginInstance.userType)
      return true
    }
    return false
  }

  return {
    handleLoginReq,
    handleLogoutJump,
    handleRouterGuardHasNotToken,
    handleJumpWithToken
  }
}
